<template>
  <el-dialog
      :before-close="hideDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="'选择优惠券，已选中' + selectedCouponList.length + '张'"
      :visible.sync="couponVisible"
      append-to-body
      width="800px">
    <!-- 券列表 -->
    <el-table :key="Math.random()" ref="cartCouponListRef" v-loading="loading" :data="cartCouponList" height="300"
              highlight-current-row
              style="width: 100%;"
              @row-click="handleRowClick">
      <el-table-column align="center" label="#" type="index" width="50"></el-table-column>
      <el-table-column align="left" label="券名称" prop="templateName" show-overflow-tooltip></el-table-column>
      <el-table-column align="left" label="券说明" prop="purpose" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" label="券类型" prop="couponTypeName" width="80"></el-table-column>
      <el-table-column align="center" label="满" prop="consumptionAmount" width="80"></el-table-column>
      <el-table-column align="center" label="减" prop="discountAmount" width="80"></el-table-column>
      <el-table-column align="center" label="状态" width="80">
        <template slot-scope="scope">
          <el-button v-if="scope.row.selected" circle icon="el-icon-check" size="small" type="success"></el-button>
          <el-button v-else circle icon="el-icon-star-off" size="small"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
    <el-button type="success" @click="hideDialog">我已选好</el-button>
  </span>
  </el-dialog>
</template>

<script>
import {mapGetters} from 'vuex'
import {couponSelect} from '@/api/settle'

export default {
  name: 'CartCouponChooseDialog',
  data () {
    return {
      warnMsg: '',
      rowId: '',
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'cartList',
      'cartVisible',
      'stationId',
      'operator',
      'cartCouponList',
      'cartOilList',
      'selectedCouponList',
      'couponVisible',
      'memberId',
      'cardUid',
      'cardMemberId'
    ])
  },
  mounted () {
    console.log('CartCouponChooseDialog mounted')
    this.$bus.$off('autoSelectCoupons')
    this.$bus.$on('autoSelectCoupons', () => {
      this.doCouponSelect('')
    })
  },
  methods: {
    hideDialog () {
      console.log('hideDialog')
      this.$store.dispatch('hideCouponDialog')
    },
    handleRowClick (row, column, event) {
      console.log('handleRowClick')
      this.rowId = row.id
      console.log(event)
      this.doCouponSelect(row.id)
    },
    // 显示警告消息
    showWarnMsg (msg) {
      if (!this.msg) {
        this.msg = msg
        this.$message.warning(this.msg)
      }
      setTimeout(() => {
        this.msg = ''
      }, 3000)
    },
    doCouponSelect (couponId) {
      console.log('doCouponSelect')
      if (!this.memberId && !this.cardUid) {
        return false
      }
      this.$store.dispatch('clearDiscountValid')
      couponSelect({
        cartItemList: this.cartList,
        cardUid: this.cardUid,
        memberId: this.memberId || this.cardMemberId, // 会员ID
        fuelRecord: this.cartOilList.length > 0 ? this.cartOilList[0].data : null, // 加油记录
        allCouponIds: this.cartCouponList.map(item => item.id).join(','), // 当前券列表ID
        selectedCouponIds: this.selectedCouponList.map(item => item.id).join(','), // 已选券ID
        toSelectCouponId: couponId// 当前要选券ID
      }).then((res) => {
        console.log('doCouponSelect res')
        console.log(res)
        if (res.data && res.data.memberId) {
          console.log('memberId=' + res.data.memberId)
        }
        if (this.cartVisible) {
          this.$store.dispatch('updateCouponSelect', res.data)
        }
        if (res.data.message) {
          this.showWarnMsg(res.data.message)
        }
      }).catch(err => {
        console.log(err)
        this.$store.dispatch('updateCouponSelect', {})
        this.$message.error(err || '请求出错！')
      })
    },
    scrollToRow (rowIndex) {
      if (rowIndex < 5) {
        return
      }
      const tableBodyWrapper = this.$refs.cartCouponListRef.$el.querySelector('.el-table__body-wrapper')
      const rowElement = this.$refs.cartCouponListRef.$el.querySelector('.el-table__row:nth-of-type(' + rowIndex + ')')
      if (tableBodyWrapper && rowElement) {
        setTimeout(() => {
          rowElement.scrollIntoView()
        }, 200)
      }
    }
  },
  watch: {
    cartCouponList () {
      this.$nextTick(() => {
        if (this.rowId) {
          console.log(this.rowId)
          for (let i = 0; i < this.cartCouponList.length; i++) {
            if (this.cartCouponList[i].id === this.rowId) {
              this.scrollToRow(i)
              break
            }
          }
        }
      })
    }
  },
  beforeDestroy () {
    // 解绑事件
    this.$bus.$off('autoSelectCoupons')
  }
}
</script>

<style>

</style>
